﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace MicroMVVM.Helpers
{
    public static class JsonSerializerHelper
    {
        /// <summary>
        /// Deserialise a string to an object.
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="json">JSON string</param>
        /// <returns>Object</returns>
        public static T Deserialize<T>(string json)
        {
            try
            {
                if (string.IsNullOrEmpty(json)) return default(T);

                var bytes = Encoding.Unicode.GetBytes(json);

                using (var stream = new MemoryStream(bytes))
                {
                    var serializer = new DataContractJsonSerializer(typeof (T));

                    return (T) serializer.ReadObject(stream);
                }
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// Serializes an object to a string.
        /// </summary>
        /// <param name="instance">Object instance</param>
        /// <returns>Serialized object</returns>
        public static string Serialize<T>(T instance)
        {
            try
            {
                if ((Equals(instance, null)) || (Equals(instance, default(T)))) return string.Empty;

                using (var stream = new MemoryStream())
                {
                    var serializer = new DataContractJsonSerializer(instance.GetType());
                    serializer.WriteObject(stream, instance);
                    stream.Position = 0;

                    using (var reader = new StreamReader(stream))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}